﻿using System.Collections.Generic;
using System.Reflection;
using System.CodeDom.Compiler;
using System.IO;
using System.Linq;
using System;
using UnityEngine;

public class Manager : MonoBehaviour
{
    private void Start()
    {
        CompilerAndRun("Main", "Run");
    }

    private void CompilerAndRun(string className, string staticMethodName)
    {
        var options = new CompilerParameters();//编译器的实例参数

        var assemblyReferences = AppDomain.CurrentDomain.GetAssemblies()
            .Where(a => !(a is System.Reflection.Emit.AssemblyBuilder) && !string.IsNullOrEmpty(a.Location))
            .Select(a => a.Location)
            .ToArray();
        options.GenerateExecutable = false;
        options.GenerateInMemory = true;
        options.ReferencedAssemblies.AddRange(assemblyReferences);

        var dirInfo = new DirectoryInfo("Scripts");
        if (!dirInfo.Exists)
        {
            Debug.LogError($"未找到脚本路径:{dirInfo.FullName}");
            return;
        }

        var csFiles = dirInfo.GetFiles("*.cs", SearchOption.AllDirectories);
        var csFilePaths = csFiles.Select((item) => item.FullName).ToArray();

        var compiler = new CSharpCompiler.CodeCompiler();
        var cr = compiler.CompileAssemblyFromFileBatch(options, csFilePaths);

        if (cr.Errors.HasErrors)
        {
            Debug.LogError("脚本编译失败");

            foreach (var item in cr.Errors)
            {
                Debug.LogError(item);
            }
        }
        else
        {
            Debug.Log($"脚本编译成功，尝试执行静态方法:{className}.{staticMethodName}");

            var runClass = cr.CompiledAssembly.GetType(className);
            runClass.InvokeMember(staticMethodName, BindingFlags.Default | BindingFlags.InvokeMethod, null, null, null);
        }
    }

}


